from contextlib import asynccontextmanager

import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import register_tortoise

from apps.api.announcements import announcements
from apps.api.category import categories
from apps.api.coach import coaches
from apps.api.dashboard import dashboard
from apps.api.login import login_in
from apps.api.program import programs
from apps.api.schedules import schedules
from apps.api.student import students
from apps.api.student_appoinment import appointments
from apps.api.student_trainings import student_trainings
from apps.api.user import users
from apps.api.user_profile import user_profiles
from settings import TORTOISE_ORM

from apps.deepseek.api import deepseek


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时执行
    from apps.deps.RSA_Maker import TimedRSAKeyGenerator
    app.state.RSA_key_generator = TimedRSAKeyGenerator()
    print("RSA密钥生成器已启动")

    yield

    # 关闭时执行
    if hasattr(app.state, 'RSA_key_generator'):
        app.state.RSA_key_generator.stop()
    print("RSA密钥生成器已停止")


app = FastAPI(lifespan=lifespan)

# 注册Tortoise ORM
register_tortoise(
    app,
    config=TORTOISE_ORM,
    generate_schemas=True,
    add_exception_handlers=True,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许的来源
    allow_credentials=True,  # 允许凭据（如 cookies）
    allow_methods=["*"],  # 允许的方法（GET, POST, PUT, DELETE 等）
    allow_headers=["*"],  # 允许的头部
)

app.include_router(users, prefix='/user', tags=['用户管理'])
app.include_router(students, prefix='/student', tags=['学员管理'])
app.include_router(coaches, prefix='/coach', tags=['教练管理'])
app.include_router(login_in, prefix='/login', tags=['登录管理'])
app.include_router(categories, prefix='/category', tags=['训练类别管理'])
app.include_router(programs, prefix='/program', tags=['训练科目管理'])
app.include_router(announcements, prefix='/announcement', tags=['公告管理'])
app.include_router(appointments, prefix='/appointment', tags=['预约管理'])
app.include_router(student_trainings, prefix='/student_training', tags=['学员训练与反馈管理'])
app.include_router(schedules, prefix='/schedule', tags=['排班管理'])
app.include_router(user_profiles, prefix='/profile', tags=['用户信息管理'])
app.include_router(dashboard, prefix='/dashboard', tags=['数据统计'])
app.include_router(deepseek, prefix='/deepseek', tags=['深度学习'])

if __name__ == '__main__':
    uvicorn.run("main:app", host='127.0.0.1', port=8000, reload=True)
